<template>
  <div class="app-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>新增商品</span>
          <el-button @click="goBack" type="primary" plain>返回列表</el-button>
        </div>
      </template>
      
      <el-form ref="goodsFormRef" :model="form" :rules="rules" label-width="120px">
        <!-- 商品分类选择 -->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="商品分类" prop="classId" required>
              <el-cascader
                v-model="selectedClassIds"
                :options="classOptions"
                :props="classProps"
                placeholder="请选择商品分类"
                clearable
                @change="handleClassChange"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="店铺内分类" prop="businessClassId">
              <el-cascader
                v-model="selectedBusinessClassIds"
                :options="businessClassOptions"
                :props="businessClassProps"
                placeholder="请选择店铺内分类"
                clearable
                @change="handleBusinessClassChange"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 基本信息 -->
        <el-divider content-position="left">基本信息</el-divider>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="商品名称" prop="goodsName" required>
              <el-input v-model="form.goodsName" placeholder="请输入商品名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="计量单位" prop="unit" required>
              <el-input v-model="form.unit" placeholder="请输入计量单位，如：个、件、kg等" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="商品状态" prop="goodsStatus" required>
              <el-switch
                v-model="form.goodsStatus"
                :active-value="1"
                :inactive-value="0"
                active-text="上架"
                inactive-text="下架"
                style="margin-left: 10px"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="商品类型" prop="goodsVirtual">
              <el-radio-group v-model="form.goodsVirtual">
                <el-radio :label="0">实物商品</el-radio>
                <el-radio :label="1">虚拟商品</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 价格设置 -->
        <el-divider content-position="left">价格设置</el-divider>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="积分价格" prop="goodsPoint">
              <el-input-number 
                v-model="form.goodsPoint" 
                :min="0" 
                :max="999999"
                style="width: 100%"
                placeholder="积分价格"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="折扣价" prop="goodsDiscount">
              <el-input-number 
                v-model="form.goodsDiscount" 
                :precision="2" 
                :min="0" 
                :max="999999"
                style="width: 100%"
                placeholder="折扣价"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="团购价" prop="goodsGroupPrice">
              <el-input-number 
                v-model="form.goodsGroupPrice" 
                :precision="2" 
                :min="0" 
                :max="999999"
                style="width: 100%"
                placeholder="团购价"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="秒杀价" prop="goodsMiaosha">
              <el-input-number 
                v-model="form.goodsMiaosha" 
                :precision="2" 
                :min="0" 
                :max="999999"
                style="width: 100%"
                placeholder="秒杀价"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="积分商品" prop="goodsPointType">
              <el-switch
                v-model="form.goodsPointType"
                :active-value="1"
                :inactive-value="0"
                active-text="是"
                inactive-text="否"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="折扣商品" prop="goodsDiscountType">
              <el-switch
                v-model="form.goodsDiscountType"
                :active-value="1"
                :inactive-value="0"
                active-text="是"
                inactive-text="否"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="秒杀商品" prop="goodsKillType">
              <el-switch
                v-model="form.goodsKillType"
                :active-value="1"
                :inactive-value="0"
                active-text="是"
                inactive-text="否"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="团购商品" prop="goodsGroupType">
              <el-switch
                v-model="form.goodsGroupType"
                :active-value="1"
                :inactive-value="0"
                active-text="是"
                inactive-text="否"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 商品图片和视频 -->
        <el-divider content-position="left">商品图片和视频</el-divider>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="商品图片" prop="goodsImg">
              <ImageUpload v-model="form.goodsImg" :limit="1" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="商品视频" prop="goodsVideo">
              <FileUpload v-model="form.goodsVideo" :limit="1" :file-type="['mp4', 'avi', 'mov']" />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 规格管理 -->
        <el-divider content-position="left">规格管理</el-divider>
        
        <div class="specs-container">
          <el-button type="primary" @click="addNewSpec" icon="Plus">新增规格</el-button>
          
          <div v-for="(specItem, specIndex) in specItems" :key="specIndex" class="spec-item">
            <el-card class="spec-card">
              <template #header>
                <div class="spec-header">
                  <span>规格项 {{ specIndex + 1 }}</span>
                  <el-button type="danger" size="small" @click="removeSpec(specIndex)">删除</el-button>
                </div>
              </template>
              
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="规格项名称">
                    <el-input v-model="specItem.specName" placeholder="如：颜色、尺寸" />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="规格值">
                    <div class="spec-values">
                      <div v-for="(value, valueIndex) in specItem.values" :key="valueIndex" class="spec-value-item">
                        <el-input v-model="specItem.values[valueIndex]" placeholder="规格值" style="width: 200px" />
                        <el-button type="danger" size="small" @click="removeSpecValue(specIndex, valueIndex)">删除</el-button>
                      </div>
                      <el-button type="primary" size="small" @click="addSpecValue(specIndex)">添加规格值</el-button>
                    </div>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-card>
          </div>
        </div>

        <!-- SKU管理 -->
        <el-divider content-position="left">SKU管理</el-divider>
        
        <div class="sku-container">
          <el-alert
            title="SKU管理说明"
            type="info"
            :closable="false"
            show-icon
            style="margin-bottom: 15px;"
          >
            <template #default>
              <p>• 商品价格将自动设置为所有SKU中的最低价格</p>
              <p>• 商品数量将自动计算为所有SKU库存的总和</p>
              <p>• 请为每个SKU填写价格、库存和货号信息</p>
            </template>
          </el-alert>
          
          <el-button type="success" @click="generateSkuList">生成SKU列表</el-button>
          
          <el-table :data="skuList" border style="width: 100%; margin-top: 20px;">
            <el-table-column label="#" type="index" width="50" />
            <el-table-column label="规格组合" min-width="200">
              <template #default="scope">
                <div class="sku-specs">
                  <el-tag v-for="(spec, index) in scope.row.specs" :key="index" type="info">
                    {{ spec.name }}: {{ spec.value }}
                  </el-tag>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="价格" width="150">
              <template #default="scope">
                <el-input v-model="scope.row.price" placeholder="价格" type="number" min="0" step="0.01">
                  <template #append>元</template>
                </el-input>
              </template>
            </el-table-column>
            <el-table-column label="库存" width="150">
              <template #default="scope">
                <el-input v-model="scope.row.stock" placeholder="库存" type="number" min="0" />
              </template>
            </el-table-column>
            <el-table-column label="货号" width="150">
              <template #default="scope">
                <el-input v-model="scope.row.skuCode" placeholder="货号" />
              </template>
            </el-table-column>
          </el-table>
        </div>

        <!-- 操作按钮 -->
        <el-form-item>
          <el-button type="primary" @click="submitForm" :loading="submitLoading">保存</el-button>
          <el-button @click="resetForm">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup name="GoodsAdd">
import * as goodsApi from "@/api/lkshop/goods";
import * as goodClassApi from "@/api/lkshop/good_class";
import * as businessClassApi from "@/api/lkshop/businessClass";
import useUserStore from "@/store/modules/user";
import ImageUpload from "@/components/ImageUpload/index.vue";
import FileUpload from "@/components/FileUpload/index.vue";

const { proxy } = getCurrentInstance();
const userStore = useUserStore();
const route = useRoute();
const router = useRouter();

const goodsFormRef = ref();
const submitLoading = ref(false);
const classOptions = ref([]);
const businessClassOptions = ref([]);
const selectedClassIds = ref([]);
const selectedBusinessClassIds = ref([]);

// 规格和SKU相关
const specItems = ref([]);
const skuList = ref([]);

// 分类选择器配置
const classProps = {
  value: 'id',
  label: 'name',
  children: 'children',
  checkStrictly: false,
  expandTrigger: 'hover' // 鼠标悬停展开
};

const businessClassProps = {
  value: 'id',
  label: 'name',
  children: 'children',
  checkStrictly: false,
  expandTrigger: 'hover' // 鼠标悬停展开
};

const form = reactive({
  goodsId: null,
  businessId: null,
  goodsName: '',
  classId: null,
  goodsPrice: null, // 商品价格不填，由SKU决定
  goodsPoint: null,
  goodsPointType: 0,
  goodsDiscountType: 0,
  goodsKillType: 0,
  goodsGroupType: 0,
  goodsGroupPrice: null,
  goodsDiscount: null,
  goodsMiaosha: null,
  goodsStatus: 1,
  goodsNumber: null, // 商品数量由SKU总和决定
  goodsImg: '',
  goodsVideo: '',
  businessClassId: null,
  goodsVirtual: 0,
  unit: ''
});

const rules = reactive({
  goodsName: [
    { required: true, message: "商品名称不能为空", trigger: "blur" }
  ],
  classId: [
    { required: true, message: "请选择商品分类", trigger: "change" }
  ],
  unit: [
    { required: true, message: "计量单位不能为空", trigger: "blur" }
  ],
  goodsStatus: [
    { required: true, message: "请选择商品状态", trigger: "change" }
  ]
});

/** 获取商品分类列表 */
function getClassList() {
  goodClassApi.getGood_classTree({}).then(response => {
    console.log('商品分类树形数据:', response.data);
    classOptions.value = response.data || [];
  }).catch((error) => {
    console.error('获取商品分类失败:', error);
    proxy.$modal.msgError("商品分类加载失败");
  });
}

/** 构建扁平数据的树形结构（备用方法） */
function buildFlatTreeData(data) {
  if (!data || data.length === 0) {
    return [];
  }

  // 按level排序
  const sortedData = data.sort((a, b) => (a.level || 0) - (b.level || 0));
  
  const result = [];
  const map = {};

  // 创建映射
  sortedData.forEach(item => {
    if (item.id) {
      map[item.id] = {
        id: item.id,
        name: item.name || item.className || '未命名分类',
        parentId: item.parentId,
        level: item.level || 1,
        children: []
      };
    }
  });

  // 构建树形结构
  sortedData.forEach(item => {
    if (item.id && map[item.id]) {
      const node = map[item.id];
      if (item.parentId && map[item.parentId]) {
        map[item.parentId].children.push(node);
      } else {
        result.push(node);
      }
    }
  });

  console.log('备用方法构建的树形数据:', result);
  return result;
}

/** 获取店铺分类列表 */
function getBusinessClassList() {
  businessClassApi.getBusinessClassTree({ businessId: userStore.businessId }).then(response => {
    console.log('店铺分类树形数据:', response.data);
    businessClassOptions.value = response.data || [];
  }).catch((error) => {
    console.error('获取店铺分类失败:', error);
    proxy.$modal.msgError("店铺分类加载失败");
  });
}

/** 构建树形数据 */
function buildTreeData(data) {
  if (!data || data.length === 0) return [];

  const map = {};
  const result = [];

  // 第一遍：创建所有节点的映射
  data.forEach(item => {
    map[item.id] = {
      ...item,
      name: item.name || item.className || '未命名分类',
      children: []
    };
  });

  // 第二遍：构建层级关系
  data.forEach(item => {
    const node = map[item.id];
    // 特殊处理parentId为0的情况
    const parentId = item.parentId === 0 ? null : item.parentId;

    if (parentId && map[parentId]) {
      map[parentId].children.push(node);
    } else if (item.parentId === 0) {
      result.push(node);
    }
  });

  return result;
}

/** 商品分类选择变化 */
function handleClassChange(value) {
  if (value && value.length > 0) {
    form.classId = value[value.length - 1];
  } else {
    form.classId = null;
  }
}

/** 店铺分类选择变化 */
function handleBusinessClassChange(value) {
  if (value && value.length > 0) {
    form.businessClassId = value[value.length - 1];
  } else {
    form.businessClassId = null;
  }
}

/** 新增规格项 */
function addNewSpec() {
  specItems.value.push({
    specName: '',
    values: ['']
  });
}

/** 删除规格项 */
function removeSpec(index) {
  specItems.value.splice(index, 1);
  generateSkuList();
}

/** 添加规格值 */
function addSpecValue(specIndex) {
  specItems.value[specIndex].values.push('');
}

/** 删除规格值 */
function removeSpecValue(specIndex, valueIndex) {
  specItems.value[specIndex].values.splice(valueIndex, 1);
  generateSkuList();
}

/** 生成SKU列表 */
function generateSkuList() {
  const validSpecItems = specItems.value.filter(item => 
    item.specName && item.values.length > 0 && item.values.some(v => v.trim())
  );

  if (validSpecItems.length === 0) {
    skuList.value = [];
    return;
  }

  const combinations = generateCombinations(validSpecItems);
  skuList.value = combinations.map(combo => ({
    specs: combo,
    price: '',
    stock: '',
    skuCode: ''
  }));
}

/** 生成规格组合 */
function generateCombinations(specItems) {
  const combinations = [];
  
  function generate(index, currentCombo) {
    if (index === specItems.length) {
      combinations.push([...currentCombo]);
      return;
    }
    
    const specItem = specItems[index];
    const validValues = specItem.values.filter(v => v.trim());
    
    for (const value of validValues) {
      currentCombo.push({
        name: specItem.specName,
        value: value.trim()
      });
      generate(index + 1, currentCombo);
      currentCombo.pop();
    }
  }
  
  generate(0, []);
  return combinations;
}



/** 提交表单 */
function submitForm() {
  proxy.$refs.goodsFormRef.validate(valid => {
    if (valid) {
      // 验证SKU数据
      if (skuList.value.length === 0) {
        proxy.$modal.msgWarning("请先生成SKU列表");
        return;
      }

      const invalidSku = skuList.value.find(sku => !sku.price || !sku.stock);
      if (invalidSku) {
        proxy.$modal.msgWarning("请填写完整的SKU信息（价格和库存）");
        return;
      }

      submitLoading.value = true;
      
      // 设置商家ID
      form.businessId = userStore.businessId;
      
      // 计算商品总数量和最低价格
      const totalStock = skuList.value.reduce((sum, sku) => sum + (parseInt(sku.stock) || 0), 0);
      const prices = skuList.value.map(sku => parseFloat(sku.price) || 0).filter(price => price > 0);
      const minPrice = prices.length > 0 ? Math.min(...prices) : 0;
      form.goodsNumber = totalStock;
      form.goodsPrice = minPrice;
      
      // 构建聚合请求数据
      const aggregateRequest = {
        goods: { ...form },
        specItems: specItems.value.map(item => ({
          specName: item.specName,
          values: item.values.filter(v => v && v.trim())
        })).filter(item => item.specName && item.values.length > 0),
        skus: skuList.value.map(sku => ({
          spec: JSON.stringify(sku.specs),
          goodsNumber: parseInt(sku.stock),
          price: parseFloat(sku.price),
          skuCode: sku.skuCode
        }))
      };
      
      // 调用聚合接口
      goodsApi.addGoodAggregate(aggregateRequest).then(response => {
        proxy.$modal.msgSuccess("新增成功");
        goBack();
      }).catch(error => {
        console.error('保存失败:', error);
        proxy.$modal.msgError("保存失败");
        submitLoading.value = false;
      });
    }
  });
}

/** 重置表单 */
function resetForm() {
  proxy.$refs.goodsFormRef.resetFields();
  selectedClassIds.value = [];
  selectedBusinessClassIds.value = [];
  specItems.value = [];
  skuList.value = [];
  Object.assign(form, {
    goodsId: null,
    businessId: null,
    goodsName: '',
    classId: null,
    goodsPrice: null, // 由SKU最低价格自动计算
    goodsPoint: null,
    goodsPointType: 0,
    goodsDiscountType: 0,
    goodsKillType: 0,
    goodsGroupType: 0,
    goodsGroupPrice: null,
    goodsDiscount: null,
    goodsMiaosha: null,
    goodsStatus: 1,
    goodsNumber: null, // 由SKU数量总和自动计算
    goodsImg: '',
    goodsVideo: '',
    businessClassId: null,
    goodsVirtual: 0,
    unit: ''
  });
}

/** 返回列表 */
function goBack() {
  router.push('/good2/goods');
}

// 初始化
getClassList();
getBusinessClassList();
</script>

<style scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.el-divider {
  margin: 20px 0;
}

/* 美化卡片 */
:deep(.el-card) {
  border-radius: 8px;
  border: 1px solid #e9ecef;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

:deep(.el-card__header) {
  background: #409eff;
  color: #ffffff;
  border-radius: 8px 8px 0 0;
  padding: 16px 20px;
  font-weight: 600;
  font-size: 18px;
}

:deep(.el-card__body) {
  padding: 24px;
}

/* 美化表单 */
:deep(.el-form-item__label) {
  font-weight: 600;
  color: #333333;
  font-size: 16px;
}

:deep(.el-input__wrapper) {
  border-radius: 6px;
  border: 1px solid #e9ecef;
  background: #ffffff;
}

:deep(.el-input__wrapper.is-focus) {
  border-color: #409eff;
}

/* 美化级联选择器 */
:deep(.el-cascader) {
  width: 100%;
}

:deep(.el-cascader .el-input__wrapper) {
  border-radius: 6px;
  border: 1px solid #e9ecef;
  background: #ffffff;
}

:deep(.el-cascader .el-input__wrapper.is-focus) {
  border-color: #409eff;
}

/* 美化数字输入框 */
:deep(.el-input-number) {
  width: 100%;
}

:deep(.el-input-number .el-input__wrapper) {
  border-radius: 6px;
  border: 1px solid #e9ecef;
  background: #ffffff;
}

/* 美化单选按钮组 */
:deep(.el-radio-group) {
  display: flex;
  gap: 20px;
}

:deep(.el-radio) {
  margin-right: 0;
}

:deep(.el-radio__input.is-checked .el-radio__inner) {
  background: #409eff;
  border-color: #409eff;
}

:deep(.el-radio__input.is-checked + .el-radio__label) {
  color: #409eff;
  font-weight: 600;
}

/* 美化按钮 */
:deep(.el-button) {
  border-radius: 6px;
  font-weight: 500;
  font-size: 14px;
}

:deep(.el-button--primary) {
  background: #409eff;
  border: 1px solid #409eff;
  color: #ffffff;
}

/* 美化分割线 */
:deep(.el-divider__text) {
  background: #ffffff;
  color: #409eff;
  font-weight: 600;
  font-size: 16px;
}

/* 美化文本域 */
:deep(.el-textarea__inner) {
  border-radius: 6px;
  border: 1px solid #e9ecef;
  background: #ffffff;
}

:deep(.el-textarea__inner:focus) {
  border-color: #409eff;
}

/* 美化上传组件 */
:deep(.el-upload) {
  border-radius: 6px;
  overflow: hidden;
}

:deep(.el-upload-dragger) {
  border-radius: 6px;
  border: 2px dashed #e9ecef;
  background: #ffffff;
}

/* 规格和SKU样式 */
.specs-container {
  margin-bottom: 20px;
}

.spec-item {
  margin-bottom: 20px;
}

.spec-card {
  border: 1px solid #e4e7ed;
}

.spec-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.spec-values {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.spec-value-item {
  display: flex;
  align-items: center;
  gap: 10px;
}

.sku-container {
  margin-bottom: 20px;
}

.sku-specs {
  display: flex;
  flex-wrap: wrap;
  gap: 5px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  :deep(.el-card__body) {
    padding: 20px;
  }
  
  :deep(.el-radio-group) {
    flex-direction: column;
    gap: 10px;
  }
}
</style>
